package org.djw.order.service.impl;

import org.djw.basic.constant.BaseConstants;
import org.djw.basic.service.impl.BaseServiceImpl;
import org.djw.basic.util.CodeGenerateUtils;
import org.djw.basic.util.DistanceUtil;
import org.djw.basic.util.PageList;
import org.djw.basic.util.QuartzJobInfo;
import org.djw.order.domain.OrderAddress;
import org.djw.order.domain.ProductOrder;
import org.djw.order.domain.ProductOrderDetail;
import org.djw.order.mapper.OrderAddressMapper;
import org.djw.order.mapper.ProductOrderDetailMapper;
import org.djw.order.mapper.ProductOrderMapper;
import org.djw.order.query.ProductOrderQuery;
import org.djw.order.service.IProductOrderService;
import org.djw.org.domain.Employee;
import org.djw.org.domain.Shop;
import org.djw.org.mapper.EmployeeMapper;
import org.djw.org.mapper.ShopMapper;
import org.djw.pay.constants.PayConstants;
import org.djw.pay.domain.PayBill;
import org.djw.pay.mapper.PayBillMapper;
import org.djw.pay.service.IPayBillService;
import org.djw.product.domain.Product;
import org.djw.product.mapper.ProductMapper;
import org.djw.quartz.service.IQuartzService;
import org.djw.user.domain.Logininfo;
import org.djw.user.domain.User;
import org.djw.user.domain.UserAddress;
import org.djw.user.mapper.UserAddressMapper;
import org.djw.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;

    @Override
    public String submit(Map<String, Object> params, Logininfo logininfo) {
        Long serviceMethod = Long.valueOf(params.get("service_method").toString());
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());// // 0 支付宝 1 微信  2 银联
        Long productId = Long.valueOf(params.get("product_id").toString());

        Product product = productMapper.loadById(productId);
        //@TODO 增加销量
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //生成服务订单
        ProductOrder productOrder = getProductOrder(params,userAddress,product,user);
        //生成统一支付标识
        String paySn = CodeGenerateUtils.generateUnionPaySn();
        productOrder.setPaySn(paySn);
        productOrderMapper.save(productOrder);
        //保存关联表 orderAdress productOrderDetail
        OrderAddress orderAddress = userAddress2orderAddress(userAddress);
        orderAddress.setOrder_id(productOrder.getId());
        orderAddress.setOrderSn(productOrder.getOrderSn());
        orderAddressMapper.save(orderAddress);

        ProductOrderDetail productOrderDetail = product2productOrderDetail(product);
        productOrderDetail.setProduct_id(product.getId());
        productOrderDetail.setOrder_id(productOrder.getId());
        productOrderDetailMapper.save(productOrderDetail);


        //生成支付单并支付
        PayBill bill = initPayBill(payMethod, user, productOrder);
        payBillMapper.save(bill);
        //支付超时定时器  掉统一的添加定时任务的接口,传递必要的参数
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        jobInfo.setJobName(BaseConstants.PAY_TIMEOUT_CANCEL_PRODUCT + productOrder.getId());//jobName
        Map<String,Object> map = new HashMap<>();
        map.put("type",BaseConstants.PAY_TIMEOUT_CANCEL_PRODUCT);
        map.put("orderId",productOrder.getId());
        jobInfo.setParams(map);//参数
        jobInfo.setFireDate(productOrder.getLastPayTime());//执行时间
        quartzService.addJob(jobInfo);
        return payBillService.pay(bill);
    }

    @Override
    public PageList<ProductOrder> admin(ProductOrderQuery query, Logininfo currentLogininfo) {
        Employee employee = employeeMapper.loadByLogininfoId(currentLogininfo.getId());
        if(employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<ProductOrder> user(ProductOrderQuery query, Logininfo currentLogininfo) {
        User user = userMapper.loadByLogininfoId(currentLogininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    private ProductOrderDetail product2productOrderDetail(Product product) {
        ProductOrderDetail productOrderDetail = new ProductOrderDetail();
        BeanUtils.copyProperties(product,productOrderDetail );
        return productOrderDetail;
    }

    private OrderAddress userAddress2orderAddress(UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setContacts(userAddress.getContacts());
        return orderAddress;
    }

    private ProductOrder getProductOrder(Map<String, Object> params, UserAddress userAddress, Product product, User user) {
        //获取前端传递的购买数量
        Long productNum = Long.parseLong(params.get("product_num").toString());
        //创建服务订单
        ProductOrder productOrder = new ProductOrder();
        //设置购买次数值
        productOrder.setDigest("[服务订单]购买"+productNum+"次"+product.getName()+"服务！");
        //设置订单状态为待支付
        productOrder.setState(0);
        //获取订单的总价,并且设置给order
        BigDecimal price  = product.getSaleprice().multiply(new BigDecimal(productNum));
        productOrder.setPrice(price);
        //获取订单编码
        productOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getLogininfo_id()));
        //设置最后支付时间
        Date lastPayTime = new Date(System.currentTimeMillis()+15*60*1000);
        productOrder.setLastPayTime(lastPayTime);
        //绑定订单服务id
        productOrder.setProduct_id(product.getId());
        System.out.println(productOrder.getProduct_id());
        //绑定用户id
        productOrder.setUser_id(user.getId());
        //绑定最近的店铺
        Shop nearestShop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(userAddress.getFullAddress()), shopMapper.loadAll());
        productOrder.setShop_id(nearestShop.getId());
        productOrder.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        return productOrder;
    }

    private PayBill initPayBill(Long payMethod, User user, ProductOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest("[摘要]对服务"+order.getOrderSn()+"支付订单！");
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setLastPayTime(order.getLastPayTime());
        bill.setPayChannel(payMethod); // 0 支付宝 1 微信  2 银联
        bill.setBusinessType(PayConstants.FUWU_ORDER);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());//冗余
        return bill;
    }

    @Override
    public void cancelOrderByQuartz(Long orderId) {
        ProductOrder productOrder = productOrderMapper.loadById(orderId);
        if(productOrder.getState() == 0){//待支付
            /**
             * 这里有很多业务坑 应该要主动去查一下
             */
            productOrder.setState(-1);
            //这里要不要去直接上架宠物自己看着办
            productOrderMapper.update(productOrder);

            System.out.println("定时任务15分钟后执行取消订单:"+productOrder.getId());
        }
    }
}
